package fdoj.eventInvitations.servlet;

import java.io.IOException;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import fdoj.eventInvitations.dao.ContactDao;
import fdoj.eventInvitations.dao.InvantationDao;
import fdoj.eventInvitations.dao.PersonDao;
import fdoj.eventInvitations.entity.Contact;
import fdoj.eventInvitations.entity.Event;
import fdoj.eventInvitations.entity.Person;

public class PrepareContactController extends HttpServlet{
	@EJB
	private ContactDao contactDao;
	@EJB
	private PersonDao personDao;
	private HttpSession session;
	private Person loggedUser;
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {

			session = request.getSession();
			loggedUser = (Person) session.getAttribute("loggedUser");
			if(loggedUser == null){
				response.sendRedirect(response.encodeRedirectURL("./index.jsp"));
				return;
			}
			String id = request.getParameter("id");
			String del = request.getParameter("del");
			Contact c = contactDao.findById(Integer.parseInt(id));
			if(del.equals("0")){
				session.setAttribute("editContact", c);
				response.sendRedirect(response.encodeRedirectURL("./editContact.jsp"));
				return;
			}else{//brisanje kontakta
				c.setValid(false);
				contactDao.merge(c);
				Person p ;
				p = personDao.findById(loggedUser.getId());
				session.setAttribute("loggedUser", p);
				response.sendRedirect(response.encodeRedirectURL("./addressbook"));
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();

		}
		response.sendRedirect(response.encodeRedirectURL("./error.jsp"));
	}
}
